Imports cmplib01
Imports FMPLib01
Imports System.Drawing
Imports System.Drawing.Drawing2D

Public Class ctlCampaignerMapControl
    Const c_MODULE As String = "ctlCampaignerMapControl"
    Const c_SELECTIONDISTANCE As Integer = 18

    Public Event BattlegroupButtonPressed(ByRef member As ChitMember)
    Public Event chitSelected(ByRef member As ChitMember)
    Public Event chitUnselected()  '// raised when a chit is unselected, and no other chit has been selected
    Public Event enemySelected(ByRef member As ChitMember)
    Public Event waypointChange() '// either added or removed
    Public Event chitDeployed(ByRef member As ChitMember)
    Public Event DeployRequest(ByVal location As Point)



    Private _deployment As Boolean = False
    Private WithEvents _cmapper As cCampaignerMapMaker
    Private _fmp As New FlexMapData
    Private _cmp As CampaignerGameData
    Private _mapOpen As Boolean = False
    Private _maponly As Boolean = True

    Private _offsetX As Integer
    Private _offsetY As Integer
    Private _zoom As Single = 1

    Private _replay As Boolean
    Private _replayPhase As Integer = 0

    Private _repositionBG As Boolean '// when the moderator presses the reposition button



    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        _cmapper = New cCampaignerMapMaker
        AddHandler _cmapper.MapRedrawn, AddressOf MapRedrawn
        picAcutalMap.BackColor = Color.Black

    End Sub

    Public Sub DrawRuleRange(ByVal range As Integer, ByVal location As Point)
        Try
            '// offset for ... offset
            Dim drawPoint As New Point(location.X - _offsetX, location.Y - _offsetY)
            _cmapper.DrawBorderedCircle(picAcutalMap.CreateGraphics, drawPoint, range, Color.Black, Color.Yellow)
        Catch ex As Exception
            HandleException(c_MODULE, ex)
        End Try
    End Sub

    Public Sub RedrawMapForCombatResolution()
        _cmapper.RedrawMapForCombatResolution()
        RenderToDisplay(picAcutalMap.CreateGraphics)
    End Sub

    Private Sub MapRedrawn()
        _cmapper.RedrawMap(_fmp, _cmp)
        RenderToDisplay(picAcutalMap.CreateGraphics)
    End Sub

    Public Sub RedrawAndRender(Optional ByVal renderphase As Integer = -1)
        If _mapOpen Then

            If _cmapper.ShowMapOnly = True Then
                _cmapper.RedrawMapOnly()
            Else
                If renderphase = -1 Then
                    _cmapper.RedrawMap(_fmp, _cmp)
                Else
                    _cmapper.RedrawMapForReplay(renderphase)
                End If
            End If

            '// now that the correct map is created, display it.
            RenderToDisplay(picAcutalMap.CreateGraphics)
        End If
    End Sub

    Public Sub RenderToDisplay(ByRef g As Graphics)
        If _mapOpen = False Then
            Exit Sub
        End If

        Dim srcRe As New RectangleF(_offsetX, _offsetY, picAcutalMap.Size.Width / _zoom, picAcutalMap.Size.Height / _zoom)
        Dim tarRe As New RectangleF(0, 0, picAcutalMap.Size.Width, picAcutalMap.Size.Height)

        '// deal with a map SMALLER than the size of the render surface... lamers.
        If ((srcRe.Width) > (tarRe.Width)) Or ((srcRe.Height > (tarRe.Width))) Then
            g.Clear(Color.Black)
        End If

        g.DrawImage(_cmapper.MapBitmap, tarRe, srcRe, GraphicsUnit.Pixel)

        If _cmapper.ShowGrid = DisplayType_dt.Normal Then _cmapper.DrawScale(g)

    End Sub

    Public Sub ClearSelectedChit()
        _cmapper.SelectedChit = Nothing
        RedrawAndRender()
    End Sub

    Public Function OpenFlexMapFromGame(ByVal ptrGame As CampaignerGameData) As Boolean
        Try

            Dim totalPath As String = System.AppDomain.CurrentDomain.BaseDirectory & "campaigns\maps"

            _fmp = _fmp.OpenMap(totalPath & ptrGame.TheaterMapFilename)
            _cmp = ptrGame

            _cmapper.CampaignerImages = New CampaignerImageLibrary

            With _cmapper.CampaignerImages
                .battleIcon = picBlast.Image
                .deadEnemy = picEnemyDead.Image
                .deadFriendly = picFriendlyDead.Image
                .heavyBridge = picHeavyBridge.Image
                .lightningBolt = picLightningBolt.Image
                .mediumBridge = picBridge.Image
                .smallBridge = picSmallBridge.Image
                .spottedEnemy = picUnknownImage.Image
                .temporaryBridge = picTempBridge.Image
                .unknownIcon = picBlankImage.Image
                .inactiveRule = picInactiveRule.Image
                .skullHighlight = picSelectedSkull.Image
                .disbanded = picDisbanded.Image
            End With

            _cmapper.showmaponly = True
            _cmapper.RedrawMap(_fmp, _cmp)

            RenderToDisplay(picAcutalMap.CreateGraphics)

            _mapOpen = True
            _cmapper.MapOpened = True

        Catch ex As Exception
            HandleException(c_MODULE, ex)
        End Try

    End Function

    Public ReadOnly Property MapBMP() As Image
        Get
            Return _cmapper.MapBitmap
        End Get
    End Property

    Public Property Deployment() As Boolean
        Get
            Return _deployment
        End Get
        Set(ByVal value As Boolean)
            _deployment = value
        End Set
    End Property

    Public Property SelectedChit() As ChitMember
        Get
            Return _cmapper.SelectedChit
        End Get
        Set(ByVal value As ChitMember)
            _cmapper.SelectedChit = value

            RedrawAndRender()
        End Set
    End Property

    Public Property ShowMapOnly() As Boolean
        Get
            Return _cmapper.ShowMapOnly
        End Get
        Set(ByVal value As Boolean)
            _cmapper.ShowMapOnly = value
        End Set
    End Property

    Public Property FlexMap() As FlexMapData
        Get
            Return _fmp
        End Get
        Set(ByVal value As FlexMapData)
            _fmp = value
            If Not _fmp Is Nothing Then _mapOpen = True

        End Set
    End Property

    Public Property cmapper() As cCampaignerMapMaker
        Get
            Return _cmapper
        End Get
        Set(ByVal value As cCampaignerMapMaker)
            _cmapper = value
        End Set
    End Property

    Private Sub picAcutalMap_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles picAcutalMap.MouseClick
        '// ok, time to select! 
        Try
            If My.Computer.Keyboard.ShiftKeyDown = True Then Exit Sub


            If e.Button = Windows.Forms.MouseButtons.Right Then
                '// waypoint stuff
                If _repositionBG Then CancelReposition()

                If _cmapper.SelectedChit Is Nothing Then Exit Sub
                If _cmapper.SelectedChit.UnitType = GroundChitClass_cgd.Objective Then Exit Sub

                '// ok! Now, get to a' waypointin! (don't forget to adjust for zoomie! and offset)
                AddWaypointToSelectedUnit(New Point((e.X / _zoom) + _offsetX, (e.Y / _zoom) + _offsetY))

            Else
                '// check for deployment
                If _deployment Then
                    DoDeploy(New Point((e.X / _zoom) + _offsetX, (e.Y / _zoom) + _offsetY))
                ElseIf _repositionBG = True Then
                    Reposition(New Point((e.X / _zoom) + _offsetX, (e.Y / _zoom) + _offsetY), e)
                Else
                    SelectChit(New Point((e.X / _zoom) + _offsetX, (e.Y / _zoom) + _offsetY))
                End If

            End If

        Catch ex As Exception

        End Try
    End Sub

    Private Sub Reposition(ByVal p As Point, ByVal e As MouseEventArgs)
        Try
            If _cmapper.SelectedChit Is Nothing Then Exit Sub
            '// right click cancels
            If e.Button = Windows.Forms.MouseButtons.Right Then
                CancelReposition()
                Exit Sub
            End If
            '// left click makes it happen
            _cmapper.SelectedChit.PreciseLocation = New PointF(p.X, p.Y)
            '// ok, here we create a log
            _cmp.LogEvents.Add(New cmplib01.CampaignerLogEvent(_cmp.selectedPlayer.PlayerName & " repositioned " & _cmapper.SelectedChit.Name, _cmp.selectedPlayer.PlayerName, _cmp.ElapsedTime.ToString, "<none>", cmplib01.EventAuthorityLevel.PublicEvent))

            CancelReposition()
            RedrawAndRender()
        Catch ex As Exception
            HandleException(c_MODULE, ex)
        End Try
    End Sub

    Private Sub CancelReposition()
        Try
            _repositionBG = False
            Me.picAcutalMap.Cursor = Cursors.Default
        Catch ex As Exception
            HandleException(c_MODULE, ex)
        End Try
    End Sub

    Private Sub DoDeploy(ByVal e As Point)
        RaiseEvent DeployRequest(e)
        'Dim DeployMan As New cDeploymentManager
        'Try
        '    If DeployMan.AttemptDeploy(_cmp, _fmp, New Point(e.X, e.Y)) = True Then
        '        RedrawAndRender()
        '        ' set up the new event for this action
        '        Dim Levent As New LogEvent
        '        Levent.Action = _cmp.selectedPlayer.PlayerName & " deployed a new unit."
        '        Levent.AuthorityLevel = EventAuthorityLevel.ModeratorEvent
        '        Levent.InvokingPlayerName = _cmp.selectedPlayer.PlayerName
        '        Levent.TurnNumber = _cmp.Turn
        '        ' add the event
        '        _cmp.LogEvents.Add(Levent.Key, Levent)
        '    End If
        'Catch ex As Exception
        '    HandleException(c_MODULE, ex)
        'End Try
    End Sub

#Region "Waypoint Stuff"
    Private Sub AddWaypointToSelectedUnit(ByVal location As Point)
        ' find the current number of waypoints, and stinking add one. Reall hard. Yah.
        'Dim i As Int32
        Dim unit As ChitMember

        Try
            ' add the waypoint
            ' if the unit is DEAD, we should not allow any new waypoints, eh?
            If Not _cmapper.SelectedChit.OwningFaction.Equals(_cmp.selectedFaction) Then Exit Sub


            unit = _cmapper.SelectedChit
            If unit.Status = GroundUnitStatus_cgd.Dead Then
                Exit Sub
            End If
            '// check if the waypoint is VALID!! :D
            Dim smar As New SmartWaypoint
            smar.LOC = location
            smar.OrderText = DirectCast(unit, BattlegroupChit).order
            smar.Speed = DirectCast(_cmapper.SelectedChit, BattlegroupChit).movementSpeed
            DirectCast(unit, BattlegroupChit).waypoints.add(smar)

            RaiseEvent waypointChange()

        Catch nullEx As NullReferenceException
            ' I guess we don't need to do anything. "we"? Who the hell is "we"?
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Sub

    'Private Sub WaypointIsInvalid(ByRef unit As UnitType)
    '    '// do a little dance to determine if the new waypoint violates... stuff.

    '    ' 1 find the start of the previous waypoint or the unit's current location
    '    ' 2 use xy strength to move along the vector at about... 3 until we reach the end.
    '    ' 3 if flexmap says the unit can't move to that location, we mark it as invalid.
    '    Dim pntA As Point
    '    Dim pntB As Point
    '    Dim distTraveled As Integer '// this is the distance we've tested
    '    Dim totalDistance As Integer '// this is how far we need to go

    '    If unit.Waypoints.Count = 1 Then
    '        pntA = unit.Location
    '        pntB = unit.Waypoints(0)
    '    Else
    '        pntA = unit.Waypoints(unit.Waypoints.Count - 2)
    '        pntB = unit.Waypoints(unit.Waypoints.Count - 1)
    '    End If

    '    Dim done As Boolean
    '    Dim xstr As Single
    '    Dim ystr As Single
    '    Dim currentPoint As Point

    '    totalDistance = XYDistance(pntA, pntB)

    '    GetXYStrength(pntA, pntB, xstr, ystr)

    '    currentPoint.X = pntA.X
    '    currentPoint.Y = pntA.Y

    '    Do Until done
    '        currentPoint.X = currentPoint.X + (3 * xstr)
    '        currentPoint.Y = currentPoint.Y + (3 * ystr)

    '        distTraveled += 6
    '        If distTraveled >= totalDistance Then Exit Do

    '        If fmvMap2.FMPData.MovementAllowed(currentPoint, unit.MovementClassID) = False Then
    '            unit.InvalidWaypoint = True
    '            Exit Sub
    '        End If
    '    Loop

    '    unit.InvalidWaypoint = False
    'End Sub

    'Private Sub DeleteUnitWaypoint()
    '    Dim unit As BattlegroupChit

    '    Try
    '        unit = DirectCast(fmvMap2.SelectedChit, BattlegroupChit)

    '        If unit.waypoints.Count > 0 Then
    '            unit.waypoints.RemoveAt(unit.waypoints.Count - 1)
    '            fmvMap2.RedrawMap()
    '        End If
    '    Catch ex As Exception
    '        HandleException(c_Module, ex)
    '    End Try
    'End Sub
#End Region


    Private Sub picAcutalMap_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles picAcutalMap.MouseMove
        If _mapOpen = False Then Exit Sub

        Dim amount As Integer = 15 '// the amount of the move

        If My.Computer.Keyboard.ShiftKeyDown Then
            If e.Button = Windows.Forms.MouseButtons.Left Then
                Static last As Point

                Dim thisP As New Point(e.X * _zoom, e.Y * _zoom)

                '// don't do nuttin if the map is smaller than view
                If picAcutalMap.Width < (_fmp.Width) Then
                    If Math.Abs(thisP.X - last.X) > 5 Then
                        If thisP.X > last.X Then
                            _offsetX -= amount '(thisp.x - last.X)
                        Else
                            _offsetX += amount '(thisp.x - last.X)
                        End If
                        '// do the ole offset check
                        If _offsetX < 0 Then _offsetX = 0

                        '// yeah, only if view is smaller
                        If (picAcutalMap.Width + _offsetX) > _fmp.Width * _zoom Then _offsetX = (_fmp.Width - (picAcutalMap.Width * _zoom))

                        last.X = thisP.X

                    End If
                Else
                    '// in case it was resized, here we go.
                    _offsetX = 0
                End If

                If picAcutalMap.Height < (_fmp.Height) Then
                    If Math.Abs(thisP.Y - last.Y) > 5 Then
                        If thisP.Y > last.Y Then
                            _offsetY -= amount '(thisp.y - last.Y)
                        Else
                            _offsetY += amount '(thisp.y - last.Y)
                        End If

                        If _offsetY < 0 Then _offsetY = 0

                        '// only works if the fmp is larger than viewable size
                        If (picAcutalMap.Height + _offsetY) > _fmp.Height Then _offsetY = _fmp.Height - picAcutalMap.Height

                        last.Y = thisP.Y
                    End If
                Else
                    _offsetY = 0
                End If

                RenderToDisplay(picAcutalMap.CreateGraphics)

            End If
        End If

        '// put in the terrain name, yahoooie!
        lblTerrain.Text = _fmp.TerrainNameAtCoord(New Point((e.X / _zoom) + _offsetX, (e.Y / _zoom) + _offsetY))
        '// if there is a unit selected, we can determine the overall movement cost for the selected map point (hopefully without being too expensive!)

        '        Try
        '            Static cost As Single

        '            pgrMovementCost.Visible = False

        '            If Not SelectedChit Is Nothing Then
        '                If SelectedChit.UnitType <> GroundChitClass_cgd.Objective Then
        '                    If SelectedChit.UnitType = GroundChitClass_cgd.Battlegroup Then
        '                        cost = _fmp.MovementCost(New Point((e.X / _zoom) + _offsetX, (e.Y / _zoom) + _offsetY), DirectCast(SelectedChit, BattlegroupChit).movementClassID)
        '                        pgrMovementCost.Value = CInt(cost)
        '                        pgrMovementCost.Visible = True
        '                    End If
        '                End If
        '            End If

        '        Catch ex As Exception

        '#If DEBUG Then
        '            Debug.WriteLine(ex.Message)
        '#End If

        '        End Try

    End Sub

    Private Sub picAcutalMap_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles picAcutalMap.Paint

        RenderToDisplay(e.Graphics)

    End Sub

    Private Sub picAcutalMap_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles picAcutalMap.Resize
        _offsetX = 0
        _offsetY = 0
        RenderToDisplay(picAcutalMap.CreateGraphics)
    End Sub

    Public Function SelectChit(ByVal pnt As Point) As Boolean
        ' returns true if a chit has been selected
        Dim lastDistance As Int16 = c_SELECTIONDISTANCE '/ ZoomFactor

        '// this is the close enough list
        Dim members As New ChitMembers
        'Dim selmem As ChitMember

        Try

            If _cmp.selectedPlayer.PlayerName = "<Moderator>" Then
                SelectByModerator(pnt)
                Exit Function
            End If

            If _cmp.selectedFaction Is Nothing Then Exit Function

            For Each mem As ChitMember In _cmp.Chits
                If mem.Status <> GroundUnitStatus_cgd.Dead Then
                    If XYDistance(pnt, mem.Location) <= c_SELECTIONDISTANCE Then
                        '// if it's an enemy, make sure it can be seen... :o
                        If mem.OwningFaction.Equals(_cmp.selectedFaction) Then
                            members.add(mem)
                        Else
                            '// it's an enemy
                            If mem.detectionLevelThisTurn > ChitDetectionLevel_cdl.Undetected Then
                                members.add(mem)
                            End If
                        End If

                    End If
                End If

            Next

            SelectChit(members, pnt)

        Catch ex As Exception
            'HandleException("FlexMapViewCampaignBuilder.SelectChit", ex)
        End Try

    End Function

    Private Sub SelectChit(ByRef members As ChitMembers, ByVal pnt As Point)
        Try
            Dim selmem As ChitMember

            Select Case members.Count
                Case Is = 0
                    Exit Sub
                Case Is = 1
                    Dim res As ChitSelectionResult

                    selmem = members.item(0)
                    res = DoSelect(selmem)
                    HandleSelectionResult(res)

                Case Is > 1
                    '// popup... goodness gracious.
                    mnuUnits.Items.Clear()
                    Dim index As Integer
                    Dim enemyMembers As New Collection


                    For Each closemember As ChitMember In members
                        If closemember.OwningFaction.Equals(_cmp.selectedFaction) Then
                            AddMenuItemForChit(closemember, index)
                            index += 1
                        Else
                            enemyMembers.Add(closemember)
                        End If


                    Next

                    '// if there are enemy in the enemy collection, make a separator and add thems.
                    If enemyMembers.Count > 0 Then
                        Dim ts As New ToolStripSeparator
                        mnuUnits.Items.Add(ts)
                        index += 1 '// for the stupid seperator
                        For Each mem As ChitMember In enemyMembers

                            AddMenuItemForChit(mem, index)
                            index += 1
                        Next

                    End If

                    mnuUnits.Show(Me, pnt.X - _offsetX, pnt.Y - _offsetY)
            End Select
        Catch ex As Exception
            HandleException(c_MODULE, ex)
        End Try
    End Sub

    Private Sub SelectByModerator(ByVal pnt As Point)
        Try
            Dim members As New ChitMembers

            For Each mem As ChitMember In _cmp.Chits
                If XYDistance(pnt, mem.Location) <= c_SELECTIONDISTANCE Then
                    members.add(mem)
                End If
            Next

            SelectChit(members, pnt)

        Catch ex As Exception
            HandleException(c_MODULE, ex)
        End Try
    End Sub

    Private Sub HandleSelectionResult(ByVal res As ChitSelectionResult)
        If res = ChitSelectionResult.ChitSelected Then
            RaiseEvent chitSelected(_cmapper.SelectedChit)
            RedrawAndRender()
        ElseIf res = ChitSelectionResult.ModeratorSelected Then
            RaiseEvent chitSelected(_cmapper.SelectedChit)
            RedrawAndRender()
        ElseIf res = ChitSelectionResult.ChitUnselected Then
            RaiseEvent chitUnselected()
            RedrawAndRender()
        ElseIf res = ChitSelectionResult.EnemySelected Then
            RaiseEvent enemySelected(_cmapper.SelectedChit)
            RedrawAndRender()
        End If
    End Sub

    Private Sub AddMenuItemForChit(ByRef mem As ChitMember, ByVal index As Integer)
        Dim sysEveHandler As New System.EventHandler(AddressOf MenuSelectChit)

        If mem.UnitType = GroundChitClass_cgd.Objective Then
            mnuUnits.Items.Add(mem.Name, DirectCast(mem, InstallationChit).ptrInstallation.Icon(0), sysEveHandler)
        Else
            mnuUnits.Items.Add(mem.Name, mem.icon, sysEveHandler)
        End If

#If DEBUG Then
        Debug.WriteLine("Adding " & mem.Name & " with index " & index)

#End If

        mnuUnits.Items(index).Tag = mem
    End Sub

    Private Function DoSelect(ByRef chit As ChitMember) As ChitSelectionResult
        Dim SelectResult As ChitSelectionResult = ChitSelectionResult.NoSelection

        Try
            If chit Is cmapper.SelectedChit Then
                cmapper.SelectedChit = Nothing
                Return ChitSelectionResult.ChitUnselected
            End If

            If _cmp.selectedPlayer.PlayerName = "<Moderator>" Then
                cmapper.SelectedChit = chit
                SelectResult = ChitSelectionResult.ModeratorSelected
            Else
                If chit.OwningFaction.Equals(_cmp.selectedFaction) Then
                    cmapper.SelectedChit = chit
                    SelectResult = ChitSelectionResult.ChitSelected
                Else
                    '// enemy
                    cmapper.SelectedChit = chit

                    SelectResult = ChitSelectionResult.EnemySelected
                End If
            End If

            Return SelectResult
        Catch ex As Exception
            HandleException("ctlCampaignerMapControl.DoSelect", ex)
        End Try

    End Function

    Private Sub MenuSelectChit(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim selmem As ChitMember = sender.tag
        Dim res As ChitSelectionResult

        res = DoSelect(selmem)

        HandleSelectionResult(res)

    End Sub


    Private Sub btnShowZoC_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowZoC.Click
        If _cmapper.MapOpened = False Then Exit Sub

        _cmapper.showZOC -= 1

        If _cmapper.showZOC < DisplayType_dt.NotShown Then _cmapper.showZOC = DisplayType_dt.Normal

        Select Case _cmapper.showZOC
            Case DisplayType_dt.Normal
                btnShowZoC.Text = "Showing All ZoC"
            Case DisplayType_dt.Reduced
                btnShowZoC.Text = "Showing Selected ZoC"
            Case DisplayType_dt.NotShown
                btnShowZoC.Text = "Hiding All ZoC"
        End Select

        RedrawAndRender()

    End Sub

    Private Sub btnShowDetection_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowDetection.Click
        If _cmapper.MapOpened = False Then Exit Sub

        _cmapper.showLOS -= 1
        If _cmapper.showLOS < DisplayType_dt.NotShown Then _cmapper.showLOS = DisplayType_dt.Normal

        Select Case _cmapper.showLOS
            Case DisplayType_dt.Normal
                btnShowDetection.Text = "Showing All Detection Ranges"
            Case DisplayType_dt.Reduced
                btnShowDetection.Text = "Showing Selected Detection Range"
            Case DisplayType_dt.NotShown
                btnShowDetection.Text = "Hiding All Detection Ranges"
        End Select

        RedrawAndRender()

    End Sub

    Private Sub btnShowWaypoints_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShowWaypoints.Click
        If _cmapper.MapOpened = False Then Exit Sub

        _cmapper.showWaypoints -= 1
        If _cmapper.showWaypoints < DisplayType_dt.NotShown Then _cmapper.showWaypoints = DisplayType_dt.Normal

        Select Case _cmapper.showWaypoints
            Case DisplayType_dt.Normal
                btnShowWaypoints.Text = "Showing All Waypoints"
            Case DisplayType_dt.Reduced
                btnShowWaypoints.Text = "Showing Selected Waypoints"
            Case DisplayType_dt.NotShown
                btnShowWaypoints.Text = "Hiding All Waypoints"
        End Select

        RedrawAndRender()

    End Sub

    Private Sub btnShowAllChits_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShowAllChits.Click
        If _cmapper.MapOpened = False Then Exit Sub

        _cmapper.ShowAllChits = Not _cmapper.ShowAllChits

        If _cmapper.ShowAllChits = True Then
            btnShowAllChits.Text = "Showing All Chits"
        Else
            btnShowAllChits.Text = "Hiding All Chits"
        End If

        RedrawAndRender()

    End Sub


    Private Sub btnShowReinforcementRange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowReinforcementRange.Click
        If _cmapper.MapOpened = False Then Exit Sub

        _cmapper.showReinforcementRange -= 1

        If _cmapper.showReinforcementRange < DisplayType_dt.NotShown Then _cmapper.showReinforcementRange = DisplayType_dt.Normal

        Select Case _cmapper.showReinforcementRange
            Case DisplayType_dt.Normal
                btnShowReinforcementRange.Text = "Showing All Reinforcement Range"
            Case DisplayType_dt.Reduced
                btnShowReinforcementRange.Text = "Showing Selected Reinforcement Ranges"
            Case DisplayType_dt.NotShown
                btnShowReinforcementRange.Text = "Hiding All Reinforcement Ranges"
        End Select

        RedrawAndRender()

    End Sub

    Private Sub btnBattlegroupSplit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBattlegroupSplit.Click
        If _mapOpen = False Then Exit Sub
        If _cmapper.SelectedChit Is Nothing Then Exit Sub
        If _cmapper.SelectedChit.UnitType = GroundChitClass_cgd.Objective Then Exit Sub

        RaiseEvent BattlegroupButtonPressed(_cmapper.SelectedChit)

    End Sub

    Private Sub btnDetection_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        'DetectionButton()
    End Sub

    Private Sub DetectionButtonPressed()
        If _cmapper.MapOpened = False Then Exit Sub
        If _cmapper.SelectedChit Is Nothing Then Exit Sub

        Dim pnt As New Point(_cmapper.SelectedChit.Location.X, _cmapper.SelectedChit.Location.Y)
        _cmapper.DrawLOSRays(picAcutalMap.CreateGraphics, pnt, _cmapper.SelectedChit.LOS, New Point(_offsetX, _offsetY), 1)

    End Sub

    Private Sub mnuShowMinimal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuShowMinimal.Click
        If _cmapper.MapOpened = False Then Exit Sub

        _cmapper.showZOC = DisplayType_dt.NotShown
        _cmapper.showLOS = DisplayType_dt.Reduced
        _cmapper.showReinforcementRange = DisplayType_dt.NotShown
        _cmapper.showWaypoints = DisplayType_dt.Reduced


        btnShowReinforcementRange.Text = "Hiding All Reinforcement Ranges"
        btnShowZoC.Text = "Hiding All ZoC"
        btnShowDetection.Text = "Showing Selected Detection Range"
        btnShowWaypoints.Text = "Showing Selected Waypoints"

        RedrawAndRender()

    End Sub

    Private Sub btnBorders_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBorders.Click
        If _cmapper.MapOpened = False Then Exit Sub

        btnBorders.Checked = Not btnBorders.Checked
        _cmapper.ShowBorders = Not _cmapper.ShowBorders
        RedrawAndRender()

    End Sub

    Private Sub btnShowBattles_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShowBattles.Click
        If _cmapper.MapOpened = False Then Exit Sub

        btnShowBattles.Checked = Not btnShowBattles.Checked

        If _cmapper.showBattles = DisplayType_dt.Normal Then
            _cmapper.showBattles = DisplayType_dt.NotShown
        Else
            _cmapper.showBattles = DisplayType_dt.Normal
        End If

        RedrawAndRender()
    End Sub

    Private Sub btnShowDeploymentZones_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShowDeploymentZones.Click
        If _cmapper.MapOpened = False Then Exit Sub

        btnShowDeploymentZones.Checked = Not btnShowDeploymentZones.Checked

        If _cmapper.showDeploymentZones = DisplayType_dt.Normal Then
            _cmapper.showDeploymentZones = DisplayType_dt.NotShown
        Else
            _cmapper.showDeploymentZones = DisplayType_dt.Normal
        End If
        RedrawAndRender()

    End Sub

    Private Sub btnShowLabels_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShowLabels.Click
        If _cmapper.MapOpened = False Then Exit Sub

        btnShowLabels.Checked = Not btnShowLabels.Checked

        _cmapper.ShowLabels = Not _cmapper.ShowLabels
        RedrawAndRender()

    End Sub

    Private Sub btnShowObjectives_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShowObjectives.Click
        If _cmapper.MapOpened = False Then Exit Sub

        btnShowObjectives.Checked = Not btnShowObjectives.Checked
        If _cmapper.showObjectives = DisplayType_dt.Normal Then
            _cmapper.showObjectives = DisplayType_dt.NotShown
        Else
            _cmapper.showObjectives = DisplayType_dt.Normal
        End If
        RedrawAndRender()
    End Sub

    Private Sub btnShowScale_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShowScale.Click
        If _cmapper.MapOpened = False Then Exit Sub

        btnShowScale.Checked = Not btnShowScale.Checked
        If _cmapper.ShowGrid = DisplayType_dt.Normal Then
            _cmapper.ShowGrid = DisplayType_dt.NotShown
        Else
            _cmapper.ShowGrid = DisplayType_dt.Normal
        End If
        RedrawAndRender()
    End Sub

    Private Sub ZoomButton(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnu110zoom.Click, mnu100zoom.Click, mnu150Zoom.Click, mnu75zoom.Click, mnu120zoom.Click, mnu80zoom.Click, mnu90zoom.Click
        '// reset the offset
        _offsetX = 0
        _offsetY = 0
        _zoom = CSng(sender.tag)
        RedrawAndRender()
    End Sub

    Private Sub btnReplay_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReplay.Click
        toggleReplay()
    End Sub

    Private Sub toggleReplay()
        If _cmp Is Nothing Then Exit Sub

        '// if its the first turn (0) don't bother replaying
        If _cmp.Turn = 0 Then Exit Sub

        _replay = Not _replay

        If _replay Then
            tmrReplay.Enabled = True
            _replayPhase = _cmp.globalPhaseCount - 50
            If _replayPhase <= 0 Then _replayPhase = 0
            prgReplayProgress.Value = 0
        Else
            _replayPhase = -1
            tmrReplay.Enabled = False
            RedrawAndRender(-1)
        End If

    End Sub

    Public Sub HaltReplay()
        If _replay = True Then toggleReplay()
    End Sub

    Private Sub tmrReplay_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmrReplay.Tick
        _replayPhase += 1
        prgReplayProgress.Value += 1

        RedrawAndRender(_replayPhase)

        If _replayPhase > _cmp.globalPhaseCount Then
            toggleReplay()
        End If

        Try
            Dim s As String = _cmp.ReplayPhaseKeysCol.Item("g-" & _replayPhase)
            lblCurrentReplayTime.Text = "[" & s & "]"
        Catch ex As Exception
            lblCurrentReplayTime.Text = "<not found>"
        End Try

        If prgReplayProgress.Value = prgReplayProgress.Maximum Then
            _replayPhase = _cmp.globalPhaseCount - 50
            If _replayPhase < 0 Then _replayPhase = 0
            prgReplayProgress.Value = 0
            toggleReplay()
        End If

    End Sub

    Public Function PixelsPerOneMile() As Single
        If _fmp Is Nothing Then Return 1
        If _fmp.MapScale.MilesPerPixelCount = 0 Then Return 1
        Return _fmp.MapScale.PixelCount / _fmp.MapScale.MilesPerPixelCount
    End Function

    Private Sub btnDeleteWaypoint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteWaypoint.Click
        If _mapOpen = False Then Exit Sub
        If _cmapper.SelectedChit Is Nothing Then Exit Sub
        If _cmapper.SelectedChit.UnitType = GroundChitClass_cgd.Objective Then Exit Sub

        Dim bg As BattlegroupChit = _cmapper.SelectedChit
        If bg.waypoints.Count = 0 Then Exit Sub

        bg.waypoints.RemoveAt(bg.waypoints.Count - 1)

        If bg.waypoints.Count = 0 AndAlso bg.invalidWaypoint = True Then bg.invalidWaypoint = False

        RaiseEvent waypointChange()

    End Sub

    Private Sub mnuNormalIcon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuNormalIcon.Click
        _cmapper.UnitSize = IconSize.Normal
        Me.RedrawAndRender()
    End Sub

    Private Sub mnuMediumIcon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuMediumIcon.Click
        _cmapper.UnitSize = IconSize.Medium
        RedrawAndRender()
    End Sub

    Private Sub mnuSmallIcon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSmallIcon.Click
        _cmapper.UnitSize = IconSize.Small
        RedrawAndRender()
    End Sub

    Private Sub mnuDetectionRange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDetectionRange.Click
        DetectionButtonPressed()
    End Sub

    Private Sub mnuCombatRange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuCombatRange.Click
        '// toggles the "combat range" overlay.
        _cmapper.ShowCombatRanges = Not _cmapper.ShowCombatRanges
        RedrawAndRender()
    End Sub

    Private Sub mnuDetectionLevels_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDetectionLevels.Click
        _cmapper.debugShowDetectionLevel = Not _cmapper.debugShowDetectionLevel
        RedrawAndRender()
    End Sub

    Private Sub _cmapper_ReplayError() Handles _cmapper.ReplayError
        tmrReplay.Enabled = False
        HaltReplay()
    End Sub

    Private Sub btnChitFilters_DropDownOpened(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnChitFilters.DropDownOpened
#If playerDebug Then
        DebugToolsToolStripMenuItem.Visible = True
#End If

    End Sub

    Public Property RepositionButtonVisible() As Boolean
        Get
            Return btnReposition.Visible
        End Get
        Set(ByVal value As Boolean)
            btnReposition.Visible = value
        End Set
    End Property

    Public Sub ModeratorLoggedIn()
        btnReposition.Visible = True
    End Sub

    Public Sub ModeratorLoggedOut()
        btnReposition.Visible = False
    End Sub

    Private Sub btnReposition_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReposition.Click
        If _cmapper.SelectedChit Is Nothing Then Exit Sub
        Try
            '// sets the flag for repositioning
            If _cmp.selectedPlayer.IgnoreRepositionMessage = False Then
                Dim f As New frmIgnorableMessage
                f.ShowDialog()
                If f.IgnoreMessage Then _cmp.selectedPlayer.IgnoreRepositionMessage = True
            End If
            _repositionBG = True
            picAcutalMap.Cursor = Cursors.Cross
        Catch ex As Exception
            HandleException(c_MODULE, ex)
        End Try
    End Sub

    Private Sub btnShowDisbanded_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowDisbanded.Click
        Try
            _cmapper.showDisbanded = Not _cmapper.showDisbanded
            btnShowDisbanded.Checked = Not btnShowDisbanded.Checked
            RedrawAndRender()
        Catch ex As Exception

        End Try
    End Sub
End Class




Public Enum ChitSelectionResult
    NoSelection = 0
    ChitSelected = 1
    EnemySelected = 2
    ChitUnselected = 3
    ModeratorSelected = 12 '// moderator has selected a chit
End Enum